from sqlalchemy import Column, Integer, String
import re
from models.base import Base, session

# task.status
STATUS_NOT_STARTED = 1  # 未开始
STATUS_PROCESSING = 2  # 处理中
STATUS_COMPLETE = 3  # 已完成

# task.type
TYPE_SECONDARY_DISTRICT = 1  # 链家二手房获取行政区
TYPE_SECONDARY_CIRCLE = 2  # 链家二手房获取商圈
TYPE_SECONDARY_LIST = 3  # 链家二手房获取列表

TYPE_RENT_DISTRICT = 4  # 链家租房获取行政区
TYPE_RENT_CIRCLE = 5  # 链家租房获取商圈
TYPE_RENT_LIST = 6  # 链家租房获取列表


class Task(Base):
    """
    任务类
    """
    __tablename__ = 'task'

    id = Column(Integer, primary_key=True)  # 任务id
    status = Column(Integer, index=True, default=STATUS_NOT_STARTED)  # 任务状态
    type = Column(Integer, nullable=False)  # 任务类型
    url = Column(String(256), index=True)  # url
    referer = Column(String(256), nullable=True, default="")  # referer，请求头的referer字段，有些反爬策略会校验

    def __repr__(self):
        return "<Task(id='%s', type=%s, url='%s')>" % (self.id, self.type, self.url)

    def process(self):
        """
        将任务的状态改为 处理中
        :return:
        """
        query = session.query(Task).filter(Task.id == self.id)
        query.update({"status": STATUS_PROCESSING})
        session.commit()
        session.refresh(self)

    def complete(self):
        """
        将任务的状态改为 已完成
        :return:
        """
        query = session.query(Task).filter(Task.id == self.id)
        query.update({"status": STATUS_COMPLETE})
        session.commit()
        print("完成:" + self.url)

    def get_host(self) -> str:
        """
        获取url的host
        :return: host
        """
        ret = re.search(r'.*?\.com', self.url)
        if ret:
            return ret.group()
        else:
            return ""
